package entity;

import utils.FileUtil;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * 切割图片，前期准备的类
 *
 * @author liangfuqiang
 * @since 2023-03-14
 */
public class CutImage {
    //每个数字起始下标
    private static final int[] IMAGE_INDEX = new int[]{
            0, 4932, 10610, 15578, 20679, 25538, 30044, 34995, 40170, 45012};
    // 小图片的宽度和高都是 28
    private static final int SIZE = 28;
    // 一行里有75 个小图片
    private static final int WIDTH = 75;
    // 有667行
    private static final int HEIGHT = 667;

    public static int getNumber(String name) {
        name = name.substring(0, name.lastIndexOf('.'));
        int i = Integer.parseInt(name);
        int j = 0;
        for (; j < IMAGE_INDEX.length - 1; j++) {
            if (i < IMAGE_INDEX[j + 1]) {
                break;
            }
        }
        return j;
    }

    private static void splitImg() throws IOException {
        BufferedImage image = ImageIO.read(new File(FileUtil.RESOURCES + "training.jpg"));

        for (int i = 0; i < HEIGHT; i++) {
            for (int j = 0; j < WIDTH; j++) {
                ImageIO.write(doSplit(j * SIZE, i * SIZE, image), "jpg", new File(FileUtil.RESOURCES + "test/" + (i * WIDTH + j) + ".jpg"));
            }
        }
    }

    private static BufferedImage doSplit(int x, int y, BufferedImage img) {
        int[] temp = new int[SIZE * SIZE];
        img.getRGB(x, y, SIZE, SIZE, temp, 0, SIZE);
        BufferedImage newImage = new BufferedImage(SIZE, SIZE, BufferedImage.TYPE_INT_ARGB);
        newImage.setRGB(0, 0, SIZE, SIZE, temp, 0, SIZE);
        return newImage;
    }

    public static void main(String[] args) throws IOException {
        splitImg();
    }
}
